/******************************************************************************
*
* This file is part of FreeTrack (http://code.google.com/p/qtfreetrack).
* BY Willy Gardiol (willy@gardiol.org)
*
* FreeTrack is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* FreeTrack is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Foobar.  If not, see <http://www.gnu.org/licenses/>
*
******************************************************************************/

#include "filenavigator.h"
#include "freetrackdialog.h"
#include "ftpushbutton.h"
#include "ftlabel.h"
#include "ftlist.h"

#define MAP_CACHE_PATH "map_cache"

QString FileNavigator::default_path()
{
    QString def_path;

#if defined(Q_OS_SYMBIAN)
        def_path = "e:\\FreeTrack\\";
#else
        QDir tmp = QDir( QDir::currentPath() );
        tmp.cdUp();
        def_path = tmp.absolutePath();
#endif
        QDir data_dir = QDir( def_path );
        if ( ! data_dir.exists() )
            if ( !data_dir.mkpath(def_path) )
            {
                data_dir = QDir( def_path = "c:\\FreeTrack\\" );
                if (!data_dir.exists())
                    if ( !data_dir.mkpath(def_path) )
                        def_path = "";
            }

    return def_path;
}

QString FileNavigator::map_cache_path()
{
    QDir data_dir = QDir( FileNavigator::default_path() );

    if ( !data_dir.exists( MAP_CACHE_PATH ) )
        data_dir.mkpath(MAP_CACHE_PATH);

    return data_dir.absoluteFilePath( MAP_CACHE_PATH );
}

QString FileNavigator::openMap(QString default_map)
{
    QStringList filters;
    filters << "*.jpg";
    filters << "*.png";
    FileNavigator* navigator = new FileNavigator(true, QObject::tr("Load map..."), default_map, filters);
    FreeTrackDialog* dialog = new FreeTrackDialog( navigator );
    if ( dialog->exec() )
    {
        QString file = navigator->getFilename();
        return file;
    }
    delete dialog;
    return "";
}

QString FileNavigator::openCal()
{
    QStringList filters;
    filters << "*.map";
    filters << "*.imp";
    filters << "*.cal";
    FileNavigator* navigator = new FileNavigator(true, QObject::tr("Load map calibration..."), "", filters);
    FreeTrackDialog* dialog = new FreeTrackDialog( navigator );

    if ( dialog->exec() )
    {
        QString file = navigator->getFilename();
        return file;
    }
    delete dialog;
    return "";
}

QString FileNavigator::openTrack(QString caption, QString default_track )
{
    QStringList filters;
    filters << "*gpx";
//    filters << "*auto";
    FileNavigator* navigator = new FileNavigator(true, caption, default_track, filters);
    FreeTrackDialog* dialog = new FreeTrackDialog( navigator );

    if ( dialog->exec() )
    {
        QString file = navigator->getFilename();
        return file;
    }
    delete dialog;
    return "";
}

QString FileNavigator::saveTrack(QString caption, QString default_track )
{
    QStringList filters;
    filters << "*gpx";
//    filters << "*auto";
    FileNavigator* navigator = new FileNavigator(false, caption, default_track, filters);
    FreeTrackDialog* dialog = new FreeTrackDialog( navigator );

    if ( dialog->exec() )
    {
        QString file = navigator->getFilename();
        if (  !file.endsWith(".gpx"))
            file += ".gpx";
        return file;
    }
    delete dialog;
    return "";
}


FileNavigator::FileNavigator(bool om, const QString& c, const QString& basepath, const QStringList& flts) :
    FreeTrackWidget(0)
{
    // set mode true == open, false == save.
    openMode = om;

    // Initialize the basepath if it is not specified
    QString my_path = ( basepath != "" ) ? basepath : FileNavigator::default_path();
    // Setup initial path and file names
    QFileInfo fi( my_path );
    QString filename = "";
    if  ( fi.isDir() )
    {
        filename = "";
        path = QDir(my_path);
    }
    else
    {
        filename = fi.fileName();
        path = QDir( fi.canonicalPath() );
    }
    path.setNameFilters( flts );
    path.setFilter( QDir::AllDirs | QDir::AllEntries | QDir::NoDotAndDotDot );
    path.setSorting( QDir::Name | QDir::IgnoreCase | QDir::DirsFirst );

    // Build the dialog widgets
    list = new FTList();
    connect( list, SIGNAL(selected(const QString&)), this, SLOT(listSelect(const QString&)));

    goup = new FTPushButton(QIcon( ":/icons/level-up.png"), BUTTON_SIZE);
    connect( goup, SIGNAL(clicked()), this, SLOT(goupSlot()));

    select = new FTPushButton( QIcon( openMode ? ":/icons/load-track.png" : ":/icons/save.png" ), BUTTON_SIZE);
    select->setEnabled( filename != "" );
    connect( select, SIGNAL(clicked()), this, SLOT(checkAccept()));

    cancel = new FTPushButton( QIcon( ":/icons/cancel.png" ), BUTTON_SIZE);
    connect( cancel, SIGNAL(clicked()), this, SIGNAL( reject()) );

    edit_filename = new QLineEdit(filename);
    connect( edit_filename, SIGNAL(textChanged(QString)), this,SLOT(filenameChanged(QString)) );
//    connect( edit_filename, SIGNAL(cursorPositionChanged(int,int)), this,SLOT(filenameChanged(int,int)) );

    folder = new FTLabel();
    caption = new FTLabel(c);
    // Hide save controls when in "open" mode
    if ( openMode )
        edit_filename->hide();

    // Show current folder in view
    populateList();
}

FileNavigator::~FileNavigator()
{
}

void FileNavigator::checkAccept()
{
    if ( !openMode )
    {
        QString filename = getFilename();
        QFileInfo fi( filename );
        if ( fi.exists() )
            if ( QMessageBox::question( this,
                                        tr("File Exists"),
                                        tr("File exists. Overwrite?") + "("+filename+")",
                                        QMessageBox::Yes|QMessageBox::No,
                                        QMessageBox::NoButton ) != QMessageBox::Yes )
                return;
    }
    emit accept();
}

void FileNavigator::goupSlot()
{
    if ( path.cdUp() )
        populateList();
}

void FileNavigator::filenameChanged(QString ns)
{
//    filename = ns;
    select->setEnabled( ns != "" );
    FTD << ns;
    FTD << "(2) " << edit_filename->text();
}

/*void FileNavigator::filenameChanged(int,int)
{
    FTD << "(3) " << edit_filename->text();
//    filename = edit_filename->text();
    select->setEnabled( true );
}*/

void FileNavigator::listSelect(const QString & file )
{
    QString full_path = path.filePath( file );
    QFileInfo fi( full_path );
    if ( fi.isDir() )
    {
        path.setPath( full_path );
        populateList();
    }
    else
    {
        edit_filename->setText( file );
        select->setEnabled(true);
    }
}

void FileNavigator::populateList()
{
    list->clear();
    if ( path.isRoot() )
    {
        QFileInfoList drives = QDir::drives();
        foreach (QFileInfo drive, drives)
            list->append( drive.absoluteFilePath() );
    }
    list->append( path.entryList() );
    folder->setText( path.canonicalPath() );
}

QString FileNavigator::getFilename()
{
    return  path.filePath( edit_filename->text() );
}

QLayout* FileNavigator::createHorizontal()
{
    QVBoxLayout* grid = new QVBoxLayout();
    grid->addWidget( caption );
    QHBoxLayout* mainGrid = new QHBoxLayout();
    mainGrid->addWidget( list );
    QVBoxLayout* rightGrid = new QVBoxLayout();
    rightGrid->addWidget( select );
    rightGrid->addWidget( goup );
    rightGrid->addWidget( cancel );
    mainGrid->addLayout( rightGrid );
    grid->addLayout( mainGrid );
    QHBoxLayout* bottomGrid = new QHBoxLayout();
    bottomGrid->addWidget( folder );
    bottomGrid->addWidget( edit_filename );
    grid->addLayout( bottomGrid );
    return grid;
}

QLayout* FileNavigator::createVertical()
{
    QVBoxLayout* grid = new QVBoxLayout();
    grid->addWidget( caption );
    grid->addWidget( list, 2 );
    grid->addWidget( folder );
    grid->addWidget( edit_filename );
    QHBoxLayout* buttonGrid = new QHBoxLayout();
    buttonGrid->addWidget( select );
    buttonGrid->addWidget( goup );
    buttonGrid->addWidget( cancel );
    grid->addLayout( buttonGrid );
    return grid;
}
